﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NCP.Recruiting.Repository.SqlServer.Data;
using NCP.Recruiting.Domain.Aggregates.Candidates;
using NCP.Recruiting.Repository.SqlServer.UnitOfWork;
using System.Data.Entity;

namespace NCP.Recruiting.Repository.SqlServer.Repositories
{
    public class CandidateRepository : Repository<Candidate>, ICandidateRepository
    {
        public CandidateRepository(MainBCUnitOfWork unitOfWork)
            : base(unitOfWork)
        {

        }

        public IQueryable<Candidate> SearchCandidates(Guid companyId, int status, string keyWord)
        {
            var list = base.GetSet()
                .Include(item => item.Jobposition)
                .Include(item => item.Resume)
                .Include(item => item.Tag)
                .DefaultIfEmpty();
            var spec = CandidateSpecifications.GetCandidatesByKeyword(keyWord)
                && CandidateSpecifications.GetCandidatesByCompanyId(companyId)
                && CandidateSpecifications.GetCandidatesByStatus(status);
            list = list.Where(spec.SatisfiedBy()).OrderByDescending(s => s.DateSaved);
            return list;
        }

        public int GetUnreadCount(Guid companyId, string keyWord)
        {
            var list = base.GetSet();
            var spec = CandidateSpecifications.GetCandidatesByKeyword(keyWord)
                && CandidateSpecifications.GetCandidatesByCompanyId(companyId);
            return list.Where(spec.SatisfiedBy()).Select(s => 1).Count();
        }

        public void DeleteByIds(List<Guid> deleteIds)
        {
            var list = base.GetSet().Where(s => deleteIds.Contains(s.Id));
            foreach (var item in list)
            {
                item.Deleted = true;
                item.LastUpdated = DateTime.Now;
                base.Modify(item);
            }
            base.UnitOfWork.Commit();
        }

        public void RecoverByIds(List<Guid> recoverIds)
        {
            var list = base.GetSet().Where(s => recoverIds.Contains(s.Id));
            foreach (var item in list)
            {
                item.Deleted = false;
                item.LastUpdated = DateTime.Now;
                base.Modify(item);
            }
            base.UnitOfWork.Commit();
        }

        public void UpdateItem(Guid id, Action<Candidate> updateFiled)
        {
            var item = base.Get(id);
            item.LastUpdated = DateTime.Now;
            updateFiled(item);
            base.Modify(item);
        }
    }
}
